package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.wdt.api.response.support.StockOutOrderTradeDTO;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.mapper.YgWholesalerDeliveryOrderDetailMapper;
import com.ygqh.baby.po.WdtQybStockOut;
import com.ygqh.baby.po.YgWholesaler;
import com.ygqh.baby.po.YgWholesalerDeliveryOrderDetail;
import com.ygqh.baby.po.YgWholesalerDeliveryOrderDetailExample;
import com.ygqh.baby.service.YgWholesalerDeliveryOrderDetailService;
import com.ygqh.baby.service.YgWholesalerService;
import com.ygqh.baby.template.AbstractSplitListTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @author Ss
 */
@Service
public class YgWholesalerDeliveryOrderDetailServiceImpl implements YgWholesalerDeliveryOrderDetailService {

    private final ExecutorService executorService = Executors.newFixedThreadPool(3);
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YgWholesalerDeliveryOrderDetailMapper ygWholesalerDeliveryOrderDetailMapper;
    @Autowired
    private YgWholesalerService ygWholesalerService;

    @Override
    public List<YgWholesalerDeliveryOrderDetail> find() {
        YgWholesalerDeliveryOrderDetailExample example = new YgWholesalerDeliveryOrderDetailExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygWholesalerDeliveryOrderDetailMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgWholesalerDeliveryOrderDetailExample example = new YgWholesalerDeliveryOrderDetailExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygWholesalerDeliveryOrderDetailMapper.countByExample(example);
    }

    @Override
    public YgWholesalerDeliveryOrderDetail findById(Long id) {
        return ygWholesalerDeliveryOrderDetailMapper.selectByPrimaryKey(id);
    }


    @Override
    public int save(YgWholesalerDeliveryOrderDetail ygWholesalerDeliveryOrderDetail) {
        return ygWholesalerDeliveryOrderDetailMapper.insertSelective(ygWholesalerDeliveryOrderDetail);
    }

    @Override
    public int update(YgWholesalerDeliveryOrderDetail ygWholesalerDeliveryOrderDetail) {
        return ygWholesalerDeliveryOrderDetailMapper.updateByPrimaryKeySelective(ygWholesalerDeliveryOrderDetail);
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        YgWholesalerDeliveryOrderDetailExample example = new YgWholesalerDeliveryOrderDetailExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgWholesalerDeliveryOrderDetail record = new YgWholesalerDeliveryOrderDetail();
        record.setStatus(DataStatus.Delete);
        return ygWholesalerDeliveryOrderDetailMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgWholesalerDeliveryOrderDetail ygWholesalerDeliveryOrderDetail) {
        int r;
        if (ygWholesalerDeliveryOrderDetail.getId() != null) {
            r = this.update(ygWholesalerDeliveryOrderDetail);
        } else {
            r = this.save(ygWholesalerDeliveryOrderDetail);
        }
        return r;
    }

    @Override
    public ResultSet<YgWholesalerDeliveryOrderDetail> search(QueryInfo queryInfo, String q) {
        List<YgWholesalerDeliveryOrderDetail> list = ygWholesalerDeliveryOrderDetailMapper.selectSuper(queryInfo, q);
        int count = ygWholesalerDeliveryOrderDetailMapper.countSuper(q);
        return new ResultSet<>(count, list);
    }

    @Override
    public void addDeliveryOrderDetailAsync(List<WdtQybStockOut> outList) {
        executorService.execute(() -> addDeliveryOrderDetail(outList));
    }

    @Override
    public void addDeliveryOrderDetailAsyncByDTO(List<StockOutOrderTradeDTO> outList) {
        executorService.execute(() -> addDeliveryOrderDetailByDTO(outList));
    }

    @Override
    public List<YgWholesalerDeliveryOrderDetail> findByShopNo(String shopNo, Date startDate, Date endDate) {
        Assert.isTrue(StringUtils.isNotBlank(shopNo), "店铺编号不能为空");
        return ygWholesalerDeliveryOrderDetailMapper.selectByShopNo(shopNo, startDate, endDate);
    }

    /**
     * 添加出库单明细
     *
     * @param outList 旺店通出库单
     */
    private void addDeliveryOrderDetail(List<WdtQybStockOut> outList) {
        if (CollectionUtils.isEmpty(outList)) {
            return;
        }
        List<YgWholesaler> wholesalerList = ygWholesalerService.findList(null, null);
        // 获取所有批发商店铺编号
        List<String> shopNoList = wholesalerList.stream().map(YgWholesaler::getShopNo).collect(Collectors.toList());
        List<WdtQybStockOut> outListByWholesaler = outList.stream().filter(o -> shopNoList.contains(o.getShopNo())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(outListByWholesaler)) {
            return;
        }
        List<Integer> stockoutIdList = outListByWholesaler.stream().map(WdtQybStockOut::getStockoutId).collect(Collectors.toList());
        // 获取已存在的出库单id
        List<Integer> existsStockoutId = this.findExistsStockoutId(stockoutIdList);
        List<YgWholesalerDeliveryOrderDetail> detailList = new ArrayList<>();
        Date now = new Date();
        List<WdtQybStockOut> repeatList = new ArrayList<>();
        outListByWholesaler.forEach(o -> {
            if (CollectionUtils.isNotEmpty(existsStockoutId) && existsStockoutId.contains(o.getStockoutId())) {
                repeatList.add(o);
            } else {
                o.getDetailsList().forEach(d -> {
                    YgWholesalerDeliveryOrderDetail detail = new YgWholesalerDeliveryOrderDetail();
                    detail.setStockoutId(o.getStockoutId());
                    detail.setShopNo(o.getShopNo());
                    detail.setShopName(o.getShopName());
                    detail.setDetailCode(d.getSrcTid());
                    detail.setDeliveryCode(o.getOrderNo());
                    detail.setWdtQybCode(o.getTradeNo());
                    detail.setSkuCode(d.getSpecNo());
                    detail.setQuantity(d.getGoodsCount().longValue());
                    detail.setDeliveryTime(o.getConsignTime());
                    detail.setCreateTime(now);
                    detailList.add(detail);
                });
            }
        });
        this.addBatch(detailList);
        logger.info("【同步旺店通出库单重复数据】--》" + JSON.toJSONString(repeatList));
    }

    private void addDeliveryOrderDetailByDTO(List<StockOutOrderTradeDTO> outList) {
        if (CollectionUtils.isEmpty(outList)) {
            return;
        }
        List<YgWholesaler> wholesalerList = ygWholesalerService.findList(null, null);
        // 获取所有批发商店铺编号
        List<String> shopNoList = wholesalerList.stream().map(YgWholesaler::getShopNo).collect(Collectors.toList());
        List<StockOutOrderTradeDTO> outListByWholesaler = outList.stream().filter(o -> shopNoList.contains(o.getShopNo())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(outListByWholesaler)) {
            return;
        }
        List<Integer> stockoutIdList = outListByWholesaler.stream().map(StockOutOrderTradeDTO::getStockoutId).collect(Collectors.toList());
        // 获取已存在的出库单id
        List<Integer> existsStockoutId = this.findExistsStockoutId(stockoutIdList);
        List<YgWholesalerDeliveryOrderDetail> detailList = new ArrayList<>();
        Date now = new Date();
        List<StockOutOrderTradeDTO> repeatList = new ArrayList<>();
        outListByWholesaler.forEach(o -> {
            if (CollectionUtils.isNotEmpty(existsStockoutId) && existsStockoutId.contains(o.getStockoutId())) {
                repeatList.add(o);
            } else {
                o.getDetailList().forEach(d -> {
                    YgWholesalerDeliveryOrderDetail detail = new YgWholesalerDeliveryOrderDetail();
                    detail.setStockoutId(o.getStockoutId());
                    detail.setShopNo(o.getShopNo());
                    detail.setShopName(o.getShopName());
                    detail.setDetailCode(d.getSrcTid());
                    detail.setDeliveryCode(o.getOrderNo());
                    detail.setWdtQybCode(o.getTradeNo());
                    detail.setSkuCode(d.getSpecNo());
                    detail.setQuantity(d.getGoodsCount().longValue());
                    detail.setDeliveryTime(o.getConsignTime());
                    detail.setCreateTime(now);
                    detailList.add(detail);
                });
            }
        });
        this.addBatch(detailList);
        logger.info("【同步旺店通出库单重复数据】--》" + JSON.toJSONString(repeatList));
    }

    /**
     * 批量添加
     *
     * @param detailList
     */
    private void addBatch(List<YgWholesalerDeliveryOrderDetail> detailList) {
        new AbstractSplitListTemplate<YgWholesalerDeliveryOrderDetail>(detailList) {
            @Override
            public int execute(List<YgWholesalerDeliveryOrderDetail> recordList) {
                return ygWholesalerDeliveryOrderDetailMapper.insertBatch(recordList);
            }
        }.split();
    }

    /**
     * 获取已存在的出库单id
     *
     * @param stockoutIdList
     * @return
     */
    private List<Integer> findExistsStockoutId(List<Integer> stockoutIdList) {
        Assert.notEmpty(stockoutIdList);
        return ygWholesalerDeliveryOrderDetailMapper.selectExistsStockoutId(stockoutIdList);
    }

}

